import React from 'react';
import CryptoJS from 'crypto-js/crypto-js';

// 获取签名
function getSignature(params = {}) {
  const { method, url, ak, sk } = params;
  var tmp = method + '\n' + url + '\n' + '' + '\n' + ak + '' + '\n' + '\n';
  // 签名
  let signature = CryptoJS.HmacSHA256(tmp, sk);
  signature = CryptoJS.enc.Base64.stringify(signature);
  return signature;
}

// 获取body
function getbody(str, sk) {
  var cont = CryptoJS.HmacSHA256(str, sk);
  cont = CryptoJS.enc.Base64.stringify(cont);
  return cont;
}

// 加密算法
export function encryptionData(params = {}) {
  const { ak, sk, method, url, body } = params;

  // 签名
  var signature = getSignature({
    method: method,
    url: url,
    ak: ak,
    sk: sk,
  });

  // 加密body
  var bodyDigest = getbody(body, sk);

  var headers = {
    'X-HMAC-SIGNATURE': signature,
    'X-HMAC-ACCESS-KEY': ak,
    'X-HMAC-ALGORITHM': 'hmac-sha256',
    'X-HMAC-DIGEST': bodyDigest,
  };
  return headers;
}

export default class extends React.Component {
  componentDidMount() {
    var params = {
      method: 'POST',
      url: '/front-manager/api/login/sendSecurityCode',
      body: JSON.stringify({ phone: '18811119999' }),
      ak: '1c25f48031b7bc89e1b25a149785ab38',
      sk: '8b395eaa1da97f325ebf9021be5f72f0',
    };
    var headers = encryptionData(params);
    console.log(headers);
  }
  render() {
    return <div>测试</div>;
  }
}
